package com.xiamo.controller;

import cn.hutool.json.JSONObject;
import com.xiamo.common.AjaxResult;
import com.xiamo.vo.WeatherVo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/weather")
public class WeatherController {

    private final String apiKey="238692a7e0f1d1dc9a9fce61c20f10f1";


    @PostMapping("/putWeather")
    public AjaxResult putWeather(WeatherVo dto) {
        String apiUrl = "https://restapi.amap.com/v3/geocode/regeo?output=json&location=" + dto.getLongitude() + "," + dto.getLatitude() + "&key=" + apiKey + "&radius=1000&extensions=all";
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(apiUrl, String.class);

        String cityCode = null;
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONObject regeocode = jsonObject.getJSONObject("regeocode");
            JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
            cityCode = addressComponent.getStr("adcode");
        } catch (Exception e) {
            return AjaxResult.error("Error parsing city code: " + e.getMessage());
        }


        if (cityCode != null) {
            String weatherApiUrl = "https://restapi.amap.com/v3/weather/weatherInfo?city=" + cityCode + "&key=" + apiKey;

            String weatherInfo = restTemplate.getForObject(weatherApiUrl, String.class);

            return AjaxResult.success(new JSONObject(weatherInfo).get("lives"));
        } else {
            return AjaxResult.error("Failed to retrieve city code");
        }
    }
}
